package com.echovin.esb.gateway.locator;

import com.echovin.esb.gateway.service.GatewayRouteService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.InMemoryRouteDefinitionRepository;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义动态路由加载器
 *
 * @author liuyadu
 */
@Slf4j
public class GatewayRouteDefinitionLocator {
    private ApplicationEventPublisher publisher;
    @Autowired
    GatewayRouteService gatewayRouteService;
    @Autowired
    InMemoryRouteDefinitionRepository repository;


    public GatewayRouteDefinitionLocator(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    /**
     * 动态加载路由
     * @return
     */
    private Mono<Void> loadRoutes() {
        // 数据库中读取路由信息
        try {
            List<RouteDefinition> routeDefinitions = gatewayRouteService.getRoutes();
            log.info("数据库加载路由配置{}", routeDefinitions);
        } catch (Exception e) {
            log.error("数据库加载路由配置异常{}", e.getMessage());
        }
        return Mono.empty();
    }

    /**
     * 刷新路由
     *
     * @return
     */
    public Mono<Void> refresh() {
        this.loadRoutes();
        // 触发默认路由刷新事件,刷新缓存路由
        this.publisher.publishEvent(new RefreshRoutesEvent(this));
        return Mono.empty();
    }

}
